﻿// 商品车调拨
function CarTransfer() {

    // 调拨单基本信息
    var CarTransferItems = new Array(
        { name: 'Id', type: 'string' },
        { name: 'ManagerUserID', type: 'string' },
        { name: 'ManagerUser', type: 'string' },
        { name: 'ApproverUserID', type: 'string' },
        { name: 'ApproverUser', type: 'string' },
        { name: 'ApproverCode', type: 'string' },
        { name: 'OutDpID', type: 'string' },
        { name: 'OutDp', type: 'string' },
        { name: 'OutDpmgUserID', type: 'string' },
        { name: 'OutDpmgUser', type: 'string' },
        { name: 'InDpID', type: 'string' },
        { name: 'InDp', type: 'string' },
        { name: 'InDpmgUserID', type: 'string' },
        { name: 'InDpmgUser', type: 'string' },
        { name: 'ExpOutTime', type: 'date' },
        { name: 'ExpInTime', type: 'date' },
        { name: 'ActOutTime', type: 'string' },
        { name: 'ActInTime', type: 'string' },
        { name: 'Description', type: 'string' }
    );

    // 机构Combo Store
    var DeptStore = new Ext.data.JsonStore({
        url: '/InfraHospUser/GetDeptList',
        root: 'data',
        totalProperty: 'total',
        id: 'Id',
        fields: [{
            name: 'Id',
            type: 'string'
        }, {
            name: 'Name',
            type: 'string'
        }, {
            name: 'Code',
            type: 'string'
        }]
    });

    var UserStore = new Ext.data.JsonStore({
        url: '/InfraHospUser/GetPlist',
        root: 'data',
        totalProperty: 'total',
        id: 'Id',
        fields: [{
            name: 'Id',
            type: 'string'
        }, {
            name: 'Name',
            type: 'string'
        }, {
            name: 'Code',
            type: 'string'
        }]
    });

    // 定义表单 商品车调拨单Reader
    var mTReader = new Ext.data.JsonReader({
        root: 'data',
        fields: CarTransferItems
    });

    // 调拨单
    var showCarTransferListGridPanel = function (itemGridStore, tbar) {
        // 定义filters
        var filters = new Ext.ux.grid.GridFilters({
            encode: true,
            filters: [{
                dataIndex: 'Brand', // 品牌
                options: ['丰田', '大众', '本田'],
                //options : TBarDeptStore.collect('Name'),
                type: 'list'
            }]
        });
        //查询语句
        filters.buildQuery = function (filters) {
            var p = {}, i, f, root, dataPrefix, key, tmp, len = filters.length;
            if (!this.encode) {
                for (i = 0; i < len; i++) {
                    f = filters[i];
                    root = [this.paramPrefix, '[', i, ']'].join('');
                    p[root + '[field]'] = f.field;

                    dataPrefix = root + '[data]';
                    for (key in f.data) {
                        p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
                    }
                }
            } else {
                tmp = [];
                for (i = 0; i < len; i++) {
                    f = filters[i];
                    tmp.push(Ext.apply({}, {
                        field: f.field
                    }, f.data));
                }
                // only build if there is active filter
                if (tmp.length > 0) {
                    p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
                }
            }
            return p;
        };

        // 机构Combo Store
        var TBarDeptStore = new Ext.data.JsonStore({
            url: '/InfraHospUser/GetDeptList',
            root: 'data',
            totalProperty: 'total',
            id: 'Id',
            fields: [{
                name: 'Id',
                type: 'string'
            }, {
                name: 'Name',
                type: 'string'
            }, {
                name: 'Code',
                type: 'string'
            }]
        });

        // 添加展场filter
        TBarDeptStore.load({
            callback: function (r) {
                filters.addFilter({
                    type: 'list',
                    dataIndex: 'CurrentDep',
                    options: JsHelper.GetFilterListData(r, 'Code', 'Name')
                });
            }
        });

        //字典Store
        var DictStore = function (dictCategory) {
            var dictionaryStore = new Ext.data.JsonStore({
                url: '/InfraDictionary/GetPlistByCategoryCode?Code=' + dictCategory,
                root: 'data',
                totalProperty: 'total',
                id: 'Code',
                fields: [{
                    name: 'Id',
                    type: 'string'
                }, {
                    name: 'Name',
                    type: 'string'
                }, {
                    name: 'Code',
                    type: 'string'
                }]
            });
            return dictionaryStore;
        }
        //与筛选有关的字典dictstore
        var DictFilterStore = function (dictCategory, filters, text, value) {
            var dictStore = DictStore(dictCategory);
            dictStore.load({
                callback: function (r) {
                    filters.addFilter({
                        type: 'list',
                        dataIndex: dictCategory,
                        options: JsHelper.GetFilterListData(r, value, text)
                    });
                }
            });
            return dictStore;
        };

        // 定义表单 商品车调拨单Reader
        var CarInfoFormReader = new Ext.data.JsonReader({
            root: 'data',
            fields: CarTransferItems
        });

        // 定义表格选择方式
        var sm = new Ext.grid.CheckboxSelectionModel();

        // 定义Grid表格列
        var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
            header: "调出仓库",
            dataIndex: 'OutDp',
            sortable: true
        }, {
            header: "调出仓管",
            dataIndex: 'OutDpmgUser',
            sortable: true
        }, {
            header: "调入仓库",
            dataIndex: 'InDp',
            sortable: true
        }, {
            header: "调入仓管",
            dataIndex: 'InDpmgUser',
            sortable: true
        }, {
            header: "经办人",
            dataIndex: 'ManagerUser',
            sortable: true
        }, {
            header: "审批人",
            dataIndex: 'ApproverUser',
            sortable: true
        }, {
            header: "状态",
            dataIndex: 'State',
            sortable: true
        }, {
            header: "描述",
            dataIndex: 'Description',
            sortable: true
        }]);

        // 设置默认定义表格工具栏
        if (!Ext.isDefined(tbar)) {
            tbar = [{
                xtype: "tbbutton",
                minWidth: 80,
                ref: '../addBtn',
                text: "添加项",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/add.png",
                handler: function (btn, e) {
                    //showEditFormWinFn(CarInfoFormReader, "添加商品车信息");
                    Fs.Car.CarForm.showCarEditFormWinFn(CarInfoFormReader, "添加商品车信息", itemGridStore)
                }
            }, "-", {
                xtype: "tbbutton",
                ref: '../delBtn',
                minWidth: 80,
                disabled: true,
                text: "删除项",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/delete.png",
                handler: function (btn, e) {
                    JsHelper.DelConfirm(function (btn) {
                        if (btn == 'yes') {
                            // gridEditor.stopEditing();
                            var s = grid.getSelectionModel().getSelections();
                            for (var i = 0, r; r = s[i]; i++) {
                                itemGridStore.remove(r);
                            }
                        }
                    });
                }
            }, "-", {
                xtype: "tbbutton",
                minWidth: 80,
                text: "双击修改项",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/pencil.png",
                disabled: true
            }, '-', '总仓:', {
                xtype: 'diccombo',
                id: 'Car_Grid_TBar_TDeport_Combobox',
                store: DictStore('TDeport'),
                width: 150,
                listWidth: 200
            }, "-", ' 展场:', {
                xtype: 'diccombo',
                id: 'Car_Gird_TBar_Dept_Combobox',
                store: TBarDeptStore,
                width: 150,
                listWidth: 200
            }, '-', {
                xtype: "tbbutton",
                minWidth: 80,
                text: "查询",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/zoom.png",
                handler: function () {
                    var tbarDeportCombobox = Ext.getCmp("Car_Grid_TBar_TDeport_Combobox");
                    var tbarDeptCombobox = Ext.getCmp("Car_Gird_TBar_Dept_Combobox");
                    if (tbarDeptCombobox.getRawValue() != "") {
                        tbarDeptComboboxValue = tbarDeptCombobox.getRawValue();
                    } else {
                        tbarDeptComboboxValue = "";
                    }
                    if (tbarDeportCombobox.getRawValue() != "") {
                        tbarDeportComboboxValue = tbarDeportCombobox.getRawValue();
                    } else {
                        tbarDeportComboboxValue = "";
                    }
                    var gridStore = grid.getStore();
                    gridStore.load({
                        params: {
                            start: 0,
                            limit: ALL_PAGESIZE_SETTING
                        }
                    });
                }
            }, "-", {
                xtype: "tbbutton",
                minWidth: 80,
                text: "重置",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/arrow_undo.png",
                handler: function () {
                    var tbarDeptCombobox = Ext.getCmp("Infra_HospUser_Gird_TBar_Dept_Combobox");
                    var tbarRoleIdCombobox = Ext.getCmp("Infra_HospUser_Gird_TBar_Role_Combobox");
                    tbarDeptCombobox.clearValue();
                    tbarRoleIdCombobox.clearValue();
                    tbarDeptComboboxValue = "";
                    tbarRoleComboboxValue = "";
                    var gridStore = grid.getStore();
                    gridStore.reload();
                }
            }];
        }

        // 分页工具栏
        var bbar = new Ext.PagingToolbar({
            displayInfo: true,
            emptyMsg: "没有数据显示",
            displayMsg: "{0}到{1}条，共{2}条",
            store: itemGridStore,
            pageSize: ALL_PAGESIZE_SETTING,
            plugins: [filters]
        });

        // 商品车信息维护表格
        var grid = new Ext.grid.GridPanel({
            enableColumnMove: false,
            sm: sm,
            cm: cm,
            plugins: [filters],
            stripeRows: true,
            frame: true,
            border: true,
            layout: "fit",
            store: itemGridStore,
            loadMask: true,
            tbar: tbar,
            bbar: bbar,
            listeners: {
                "rowdblclick": function (g, rowIndex, e) {
                    var store = g.getStore()
                    var id = store.getAt(rowIndex).get("Id");
                    //alert(rowIndex);
                    //alert('store ' + store.getAt(rowIndex).get("Id"));
                    //Fs.Car.CarForm.showCarEditFormWinFn(CarInfoFormReader, "商品车信息", itemGridStore, id)
                    var formLoadArgs = {
                        url: '/CarTransfer/GetById',
                        params: {
                            'Id': id
                        },
                        waitMsg: '数据加载中...'
                    };
                    formTransferForm.load(formLoadArgs);
                }
            }
        });

        // 控制删除按钮
        grid.getSelectionModel().on('selectionchange', function (sm) {
            grid.delBtn.setDisabled(sm.getCount() < 1);
        });

        itemGridStore.load({
            params: {
                start: 0,
                limit: ALL_PAGESIZE_SETTING
            }
        });

        return grid;
    };

    // 调拨单
    var StoreTransferList = new Ext.data.Store({
        url: '/CarTransfer/QueryPlist',
        remoteSort: true,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'total',
            id: 'Id',
            fields: CarTransferItems
        })
    });
    StoreTransferList.setDefaultSort('CreateTime', 'ASC'); // 设置默认排序

    // 左侧库存汽车清单
    var gridTransferList = showCarTransferListGridPanel(StoreTransferList);
    gridTransferList.region = 'west';
    gridTransferList.width = 400;
    
    // 右侧调拨单部分

    function getCarById(qid, itemGridStore) {
        var carSingleStore = new Ext.data.Store({
            url: '/Car/QueryCarList?query=' + qid,
            remoteSort: true,
            reader: new Ext.data.JsonReader({
                root: 'data',
                totalProperty: 'total',
                id: 'Id',
                fields: Fs.Car.CarForm.CarBaseField
            })
        });
        carSingleStore.load({
            callback: function (r) {
                alert('返回记录：' + carSingleStore.data.getCount());
                itemGridStore.add(carSingleStore.getAt(0));
            }
        });
    };

    //tbar
    function transTBar(itemGridStore) {
        tbar = [
            ' 快速查找：', '-',
            {
                xtype: 'textfield',
                width: 150,
                id: 'q_query'
            },
            {
                xtype: "tbbutton",
                minWidth: 80,
                ref: '../addBtn',
                text: " 添加",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/add.png",
                handler: function (btn, e) {
                    var qid = Ext.getCmp("q_query").getValue();
                    //alert('qid is : ' + qid);
                    getCarById(qid, itemGridStore);
                }
            }, "-", {
                xtype: "tbbutton",
                ref: '../delBtn',
                minWidth: 80,
                disabled: true,
                text: "删除项",
                cls: "x-btn-text-icon",
                icon: "/Content/icons/delete.png",
                handler: function (btn, e) {
                    JsHelper.DelConfirm(function (btn) {
                        if (btn == 'yes') {
                            // gridEditor.stopEditing();
                            var s = gridTransferCars.getSelectionModel().getSelections();
                            for (var i = 0, r; r = s[i]; i++) {
                                itemGridStore.remove(r);
                            }
                        }
                    });
                }
            }];
        return tbar;
    };

    var StoreTransferCars = new Ext.data.Store({
        url: './',
        remoteSort: true,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'total',
            id: 'Id',
            fields: Fs.Car.CarForm.CarBaseField
        })
    });

    StoreTransferCars.setDefaultSort('CreateTime', 'ASC'); // 设置默认排序

    var gridTransferCars = Fs.Car.CarForm.showCarListGridPanel(StoreTransferCars, transTBar(StoreTransferCars));
    gridTransferCars.region = 'center';

    var firstColumn = [{
        fieldLabel: '调出仓库<span style="color: red;" >*</span>',
        xtype: 'idccombo',
        id: 'OutDp',
        hiddenName: 'OutDpID',
        store: DeptStore,
        width: 150,
        listWidth: 200
    }, {
        fieldLabel: '调出仓管<span style="color: red;" >*</span>',
        xtype: 'idccombo',
        id: 'OutDpmgUser',
        hiddenName: 'OutDpmgUserID',
        store: UserStore,
        width: 150,
        listWidth: 200
    }, { 
        fieldLabel: '调入仓库<span style="color: red;" >*</span>',
        xtype: 'idccombo',
        id: 'InDp',
        hiddenName: 'InDpID',
        store: DeptStore,
        width: 150,
        listWidth: 200
    }, {
        fieldLabel: '调入仓管<span style="color: red;" >*</span>',
        xtype: 'idccombo',
        id: 'InDpmgUser',
        hiddenName: 'InDpmgUserID',
        store: UserStore,
        width: 150,
        listWidth: 200
    }, {
        fieldLabel: '经办人',
        xtype: 'idccombo',
        hiddenName: 'ManagerUserID',
        id: 'ManagerUser',
        store: UserStore,
        width: 150        
    }, {
        fieldLabel: '审批人',
        xtype: 'idccombo',
        width: 150,
        store: UserStore,
        id: 'ApproverUser',
        hiddenName: 'ApproverUserID'
    }];

    var secondColumn = [{
        fieldLabel: '预计出发',
        xtype: 'datefield',
        width: 150,
        name: 'ExpOutTime',
        value: new Date(),
        readOnly: true,
        //disabled: true,
        hideTrigger: true,
        format:'Y-m-d H:i:s'
    }, {
        fieldLabel: '预计到达',
        xtype: 'datefield',
        width: 150,
        name: 'ExpInTime',
        value: new Date().add(Date.HOUR, 2),
        readOnly: true,
        //disabled: true,
        format:'Y-m-d H:i:s'
    }, {
        fieldLabel: '实际出发',
        xtype: 'datefield',
        width: 150,
        name: 'ActOutTime',
        //value: new Date(),
        format: 'Y-m-d H:i:s'
    }, {
        fieldLabel: '实际到达',
        xtype: 'datefield',
        width: 150,
        name: 'ActInTime',
        //value: new Date().add(Date.HOUR, 2),
        format: 'Y-m-d H:i:s'
    }];

    // 调拨单Fieldset
    var fieldsetTransfer = new Ext.form.FieldSet({
        title: '商品车调拨单',
        region: 'north',
        //autoHeight: true,
        height : 200,
        layout: 'column',
        labelWidth: 60,
        labelAlign: 'right',
        //bodyStyle: 'padding:5px 5px 0',
        // 请改变下面的items
        // 并在上面定义每个列的组件集合
        items: [{
            xtype: 'container',
            autoEl:{},
            columnWidth : 0.5,
            layout : 'form',
            items: firstColumn
        }, {
            xtype: 'container',
            autoEl:{},
            columnWidth : 0.5,
            layout : 'form',
            items: secondColumn
        }]        
    });

    // 右侧调拨单Tranform
    var formTransferForm = new Ext.FormPanel({
        layout: 'border',
        region: 'center',
        reader: mTReader,
        items: [fieldsetTransfer, gridTransferCars],
        buttonAlign: 'center',
        buttons: [new Ext.ux.SubmitBtn({
            handler: function () {
                if (formTransferForm.getForm().isValid()) {
                    formTransferForm.getForm().submit({
                        url: '/CarTransfer/SaveOrUpdate',
                        params: {
                            // 这个地方处理金额取值问题
                            Id: "",
                            ManagerUser: Ext.getCmp('ManagerUser').getRawValue(),
                            ApproverUser: Ext.getCmp('ApproverUser').getRawValue(),
                            OutDp: Ext.getCmp('OutDp').getRawValue(),
                            OutDpmgUser: Ext.getCmp('OutDpmgUser').getRawValue(),
                            InDp: Ext.getCmp('InDp').getRawValue(),
                            InDpmgUser: Ext.getCmp('InDpmgUser').getRawValue(),
                            Cars: StoreTransferCars.collect('Id')
                        },
                        success: function (form, action) {
                            itemGridStore.setDefaultSort('CreateTime', 'DESC');
                            itemGridStore.load({// 刷新表格
                                params: {
                                    start: 0,
                                    limit: ALL_PAGESIZE_SETTING
                                }
                            });
                            //win.destroy(); // 关闭窗口
                        },
                        failure: function (form, action) {
                            JsHelper.ShowError(action.result.msg);
                        }
                    }); // formSubmitArgs
                    // 引用之前定义的请求参数变量
                }
            }
        }), new Ext.ux.CancelBtn({
            handler: function () {
                formTransferForm.getForm().reset();
            }
        })]
    });
    formTransferForm.region = 'center';
    formTransferForm.width = 400;

    formTransferForm.form.setValues = function (values) {
        if (Ext.isArray(values)) { // array of objects
            for (var i = 0, len = values.length; i < len; i++) {
                var v = values[i];
                var f = this.findField(v.id);
                if (f) {
                    f.setValue(v.value);
                    if (this.trackResetOnLoad) {
                        f.originalValue = f.getValue();
                    }
                }
            }
        } else { // object hash
            var field, id;
            for (id in values) {
                if (id == "JobType" && values[id] == "") {
                    continue;
                }
                if (!Ext.isFunction(values[id]) && (field = this.findField(id))) {
                    field.setValue(values[id]);
                    if (this.trackResetOnLoad) {
                        field.originalValue = field.getValue();
                    }
                }
            }
        }
        return this;
    }
    

    // 创建框架
    var main = new Ext.Panel({
        border: false,
        layout: 'border',
        items: [gridTransferList, formTransferForm]
    });

    // 加载框架
    JsHelper.ExtTabDoLayout(main);
};

CarTransfer();
